package com.example.menuvirtualclient.repository;

import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

import com.example.menuvirtualclient.core.*;
import com.example.menuvirtualclient.data.Repository;

public class OrderRepository extends Repository<Order> {

	private static final String LOGTAG = "OrderRepository";
	private TableRepository _tableRepository;
	private UserRepository _userRepository;
	
	public OrderRepository(Context context) {
		super(context);
		_tableRepository = new TableRepository(context);
		_userRepository = new UserRepository(context);
	}

	@Override
	public String getTableName() {
		return "Orders";
	}
		
	@Override
	public Order Get(long id) {
		SQLiteDatabase db = null;
		Order entity = null;
		String[] filter = new String[1];
		filter[0] = Long.toString(id);
		try{
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();			
			Cursor cursor = db.rawQuery("SELECT id, status, (strftime('%s',date)*1000), tableid, userid FROM Orders WHERE id = ?", filter);
			
			cursor.moveToFirst();
			entity = BuildNewEntity(cursor); 
			cursor.close();
		    db.close();
		}
		catch(Exception ex){
			Log.e(LOGTAG, ex.getMessage());			
		}
		finally{
			if(db != null)
				if(db.isOpen()) {
					db.close();
					Log.e(LOGTAG, "Close database");		
				}
		}
		return entity;
	}
	
	@Override
	public void Insert(Order entity) {
		SQLiteDatabase db = null;
		try{
			ContentValues newRow = new ContentValues();
			newRow.put("id", entity.getId());
			newRow.put("status", entity.getStatus());
			//newRow.put("date", entity.getDate());
			newRow.put("tableid", entity.getTableId());
			newRow.put("userid", entity.getUserId());
			
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();
			db.insert(getTableName(), null, newRow);
			
			db.close();
		}
		catch(NullPointerException ex){
			Log.e(LOGTAG, ex.getMessage());
		}
		catch(SQLiteException ex){
			Log.e(LOGTAG, ex.getMessage());
		}
		catch(Exception ex){
			Log.e(LOGTAG, ex.getMessage());		
		}
		finally{
			if(db != null)
				if(db.isOpen()) db.close();
		}
	}
	
	@Override
	public Order BuildNewEntity(Cursor cursor) {
		Order order = new Order();
		order.setId(cursor.getInt(0));
		order.setStatus(cursor.getInt(1));
		long miliseconds = cursor.getLong(2);
		Date date = new Date(miliseconds);
		order.setDate(date);
		order.setTableId(cursor.getInt(3));
		order.setUserId(cursor.getInt(4));
		
		return order;
	}
}
